package com.dyh.quickdemozwei.mja;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;

import java.util.ArrayList;
import java.util.List;

public class MainLog2 {



    /*不能有Slf4 注解 否则加载2*/

    public static void main(String[] args) throws Exception {


        ClassPool pool = ClassPool.getDefault();

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        CachingMetadataReaderFactory factory = new CachingMetadataReaderFactory();

        CtClass targetctClass = null;
        try {

            Resource[] resources = resolver.getResources("ch/qos/logback/classic/**/*.class");


            List<CtClass> ctClasses = new ArrayList<>();
            for (Resource resource : resources) {
                MetadataReader reader = factory.getMetadataReader(resource);
                ClassMetadata metadata = reader.getClassMetadata();


                if (metadata.getClassName().endsWith(".Logger")) {
                    CtClass ctClass = pool.getCtClass(metadata.getClassName());
                    targetctClass = ctClass;
                    for (CtMethod method : ctClass.getMethods()) {

                        if (method.getName().startsWith("error")) {
                            method.insertBefore("System.out.println(\"我在最后插入了\");");
                        }
                    }


                }

            }

            for (CtClass ctClass : ctClasses) {
                try {
                    ctClass.toClass();
                } catch (Exception e) {
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }


//        Logger logger = LoggerFactory.getLogger(Main.class);
        Logger logger = (Logger) targetctClass.toClass().newInstance();
        logger.error("dawdaw {}", "111");
        System.out.println();

        /*ch/qos/logback/classic/Logger"*/
    }
}

